package sputils

import (
	"fmt"
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/gobase/subpub"
	"gitee.com/ymofen/golog"
	"io"
	"runtime"
	"sync"
	"sync/atomic"
)

type SpBaseSub struct {
	logger           golog.Logger
	lk               sync.RWMutex
	subSessionPrefix string
	subsessionid     string
	subconnstr       string
	stepMsg          string
	errmsg           string

	conf          gobase.StrMap
	objectRef     *gobase.ObjectInnerRef
	sub           subpub.ISubA
	subTopics     map[string]struct{}
	defaultTopics string
}

var (
	subsessionN   int32
	baseSubAliveN int32
)

func GetBaseSubAliveN() int32 {
	return atomic.LoadInt32(&baseSubAliveN)
}

// subprefix 创建session时的前缀
func NewSpBaseSub(subprefix string) *SpBaseSub {
	rval := &SpBaseSub{subSessionPrefix: subprefix, logger: golog.Default()}
	atomic.AddInt32(&baseSubAliveN, 1)
	runtime.SetFinalizer(rval, func(obj interface{}) {
		atomic.AddInt32(&baseSubAliveN, -1)
	})
	return rval
}

func (this *SpBaseSub) GetSubSessionID() string {
	return this.subsessionid
}

func (this *SpBaseSub) GetDefaultTopic() string {
	return this.defaultTopics
}

func (this *SpBaseSub) ConfString() string {
	return this.subconnstr
}

func (this *SpBaseSub) StatusText() string {
	this.lk.RLock()
	defer this.lk.RUnlock()
	objRef := this.objectRef
	if objRef == nil {
		return fmt.Sprintf("%s, step:%s", this.ConfString(), this.stepMsg)
	}
	s := objRef.GetStatus()
	if len(s) == 0 {
		return fmt.Sprintf("%s, step:%s", this.ConfString(), this.stepMsg)
	} else {
		return fmt.Sprintf("%s, %s", this.ConfString(), s)
	}
}

func (this *SpBaseSub) GetKeyValue(key string) (val interface{}, ok bool) {
	this.lk.RLock()
	defer this.lk.RUnlock()
	objRef := this.objectRef
	if objRef == nil {
		return
	}
	if lvIntf, ok1 := objRef.GetObject().(KeyValueGetter); ok1 {
		return lvIntf.GetKeyValue(key)
	}

	return
}

func (this *SpBaseSub) GetStatus(args ...interface{}) string {
	this.lk.RLock()
	defer this.lk.RUnlock()
	objRef := this.objectRef
	if objRef == nil {
		return fmt.Sprintf("%s, step:%s", this.ConfString(), this.stepMsg)
	}
	return objRef.GetStatus(args...)
}

// lk mustbe held
func (this *SpBaseSub) closeSub() {
	if this.objectRef != nil {
		this.stepMsg = fmt.Sprintf("[%s]closeSub->DelSession:0", gobase.NowString())
		sub := this.sub
		if sub != nil && len(this.subTopics) > 0 {
			for k, _ := range this.subTopics {
				sub.Unsub(this.subsessionid, k)
			}
			this.subTopics = nil
		}

		this.objectRef.ReleaseRef()
		this.objectRef = nil
		this.sub = nil
		this.stepMsg = fmt.Sprintf("[%s]closeSub->DelSession:1", gobase.NowString())
		this.subsessionid = ""
		this.subconnstr = ""

	}
}

// 只停止当前， 不清理
func (this *SpBaseSub) Stop() {
	this.lk.Lock()
	defer this.lk.Unlock()
	this.closeSub()
}

// 清理不再使用
func (this *SpBaseSub) Close() error {
	this.lk.Lock()
	defer this.lk.Unlock()
	if len(this.subsessionid) == 0 {
		return io.ErrClosedPipe
	}
	this.closeSub()
	this.logger = nil
	return nil
}

func (this *SpBaseSub) SetLogger(logger golog.Logger) {
	this.logger = logger
}

func (this *SpBaseSub) checkGetObj(conf gobase.StrMap) (*gobase.ObjectInnerRef, error) {
	conntype := conf.StringByName("conntype", "")
	conntype = fmt.Sprintf("sp.%s", conntype)
	obj, err := gobase.CreateFactoryInstance(conntype, conf)
	if err != nil {
		return nil, err
	}

	if lvintf, ok := obj.(*gobase.ObjectInnerRef); ok {
		return lvintf, nil
	} else {
		return nil, fmt.Errorf("%s:%s is not an object of [gobase.ObjectInnerRef]", conntype, ObjectType(obj))
	}
}

func (this *SpBaseSub) ObjectFunc(fn func(obj interface{}) error) error {
	this.lk.RLock()
	defer this.lk.RUnlock()
	objRef := this.objectRef
	if objRef == nil {
		return gobase.ErrInvalidObject
	}
	return fn(objRef.GetObject())
}

func (this *SpBaseSub) HealthyCheck() (healthy gobase.Ternary, msg string) {
	this.lk.RLock()
	defer this.lk.RUnlock()

	if this.logger == nil {
		return gobase.TernaryFalse, "closed"
	}

	if this.sub == nil {
		return gobase.TernaryFalse, "sub is nil"
	}

	if this.objectRef == nil {
		return gobase.TernaryFalse, "objectRef is nil"
	}
	obj := this.objectRef.GetObject()
	if obj == nil {
		return gobase.TernaryFalse, "inner object is nil"
	}

	if lvIntf, ok := obj.(HealthyTernaryChecker); ok {
		return lvIntf.HealthyCheck()
	}

	if lvIntf, ok := obj.(HealthyInt8Checker); ok {
		v1, msg1 := lvIntf.HealthyCheck()
		return gobase.Ternary(v1), msg1
	}

	if lvIntf, ok := obj.(HealthyChecker); ok {
		v1, msg1 := lvIntf.HealthyCheck()
		if v1 {
			return gobase.TernaryTrue, msg1
		}
		return gobase.TernaryFalse, msg1
	}
	return
}

// 需要inner支持pub接口
func (this *SpBaseSub) Pub(topic string, max int, args ...interface{}) int {
	this.lk.RLock()
	defer this.lk.RUnlock()
	objRef := this.objectRef
	if objRef == nil {
		return -1
	}
	if pub, ok := objRef.GetObject().(subpub.IPub); ok {
		return pub.Pub(topic, max, args...)
	}
	return -1
}

func (this *SpBaseSub) ExecuteAction(action int, args ...interface{}) (r interface{}, err error) {
	this.lk.RLock()
	defer this.lk.RUnlock()
	objRef := this.objectRef
	if objRef == nil {
		return nil, ErrInvalidObject
	}
	return objRef.ExecuteAction(action, args...)
}

func (this *SpBaseSub) ReloadConf(conf SuperValue, notifyfn subpub.SubFunc) error {
	confMap := gobase.NewStrMap()
	if !CheckIsNil(conf) {
		if conf.IsString() {
			confMap.URLFormDecode(conf.String())
		} else if conf.IsObject() {
			url := conf.StringByName("url", "")
			if len(url) > 0 {
				confMap.URLFormDecode(url)
			}
			conf.Write2StrMap(confMap)
		}
	}
	return this.ReloadConfMap(confMap, notifyfn)
}

func (this *SpBaseSub) ReloadConfString(str string, notify subpub.SubFunc) error {
	confMap := gobase.NewStrMap()
	confMap.URLFormDecode(str)
	return this.ReloadConfMap(confMap, notify)
}

func (this *SpBaseSub) ReloadConfMap(confMap gobase.StrMap, notify subpub.SubFunc) error {
	this.lk.Lock()
	defer this.lk.Unlock()
	if confMap == nil {
		this.closeSub()
		return nil
	}

	str := confMap.Encode("=", ";")
	if str == this.subconnstr {
		return nil
	} else {
		this.closeSub()
	}

	this.subconnstr = str
	return this.checkSub(confMap, notify)
}

// lk must be held
func (this *SpBaseSub) checkSub(confMap gobase.StrMap, notify subpub.SubFunc) error {
	if len(this.subsessionid) == 0 {
		this.subsessionid = fmt.Sprintf("%s-sub-%d", this.subSessionPrefix, atomic.AddInt32(&subsessionN, 1))
	}
	this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:0", gobase.NowString())
	objref, err := this.checkGetObj(confMap)
	if err != nil {
		this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:-1, err:%s", gobase.NowString(), err.Error())
		this.logger.Warnf("create plug fail, args:%s, err:%s", confMap.URLEncode0(), err.Error())
		return err
	} else if objref == nil {
		this.stepMsg = fmt.Sprintf("[%s]checkPubNode->checkGetObj:-1, err:%s", gobase.NowString(), "objref is null")
		return fmt.Errorf("create fail, args:%s", confMap.URLEncode0())
	} else {
		innerObj := objref.GetObject()
		if innerObj == nil {
			this.stepMsg = fmt.Sprintf("[%s]checkPubNode->checkGetObj:-1, err:%s", gobase.NowString(), "innerObj is null")
			objref.ReleaseRef()
			return fmt.Errorf("inner object is nil, args:%s", confMap.URLEncode0())
		}
		this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:1", gobase.NowString())
		this.objectRef = objref
		//var subArg interface{}
		//if vInf, ok := innerObj.(ArgsConverter); ok {
		//	subArg = vInf.ConvertArgs(0, confMap)
		//}

		err = this.objectRef.CheckStart()
		if err == gobase.ErrUnsupported {
			this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:2, checkstart unsupoort!", gobase.NowString())
		} else if err != nil {
			this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:2, checkstart err:%s", gobase.NowString(), err.Error())
		} else {
			this.stepMsg = fmt.Sprintf("[%s]checkSub->AddSession:2", gobase.NowString())
		}

		this.sub = innerObj.(subpub.ISubA)
		subtopics := make(map[string]struct{})

		if confMap.IntByName("evt", 1) == 1 {
			this.sub.Sub(this.subsessionid, SpEvtNotifyExt, notify)
			this.sub.Sub(this.subsessionid, SpEvtNotify, notify)
			this.sub.Sub(this.subsessionid, SpEvtExchange, notify)
			subtopics[SpEvtNotifyExt] = struct{}{}
			subtopics[SpEvtNotify] = struct{}{}
			subtopics[SpEvtExchange] = struct{}{}
		}

		topic := confMap.StringByName("topic", "")
		if len(topic) == 0 {
			topic = SpDefaultChannel
		}
		this.defaultTopics = topic

		this.sub.Sub(this.subsessionid, topic, notify)
		subtopics[topic] = struct{}{}
		this.subTopics = subtopics
		return nil
	}
}
